<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="文章详情"> 文章详细信息 </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard" size="small" :segmented="{ content: true }">
      <n-descriptions label-placement="left" class="py-2">
        <n-descriptions-item>
          <template #label>文章ID</template>
          {{ article.articleID }}
        </n-descriptions-item>
        <n-descriptions-item label="标题">{{ article.title }}</n-descriptions-item>
        <n-descriptions-item label="作者ID">{{ article.authorID }}</n-descriptions-item>
        <n-descriptions-item label="创建时间">{{ formatDate(article.creationTime) }}</n-descriptions-item>
        <n-descriptions-item label="收藏数">{{ article.favoriteCount }}</n-descriptions-item>
        <n-descriptions-item label="评论数">{{ article.commentCount }}</n-descriptions-item>
        <n-descriptions-item label="标签">
          <n-space>
            <n-tag v-for="tag in parseTags(article.tag)" :key="tag" type="info" round size="small">{{ tag }}</n-tag>
            <span v-if="parseTags(article.tag).length === 0">无标签</span>
          </n-space>
        </n-descriptions-item>
        <n-descriptions-item label="状态">
          <n-tag :type="getStatusType(article.status)">{{ getStatusText(article.status) }}</n-tag>
        </n-descriptions-item>
      </n-descriptions>

      <n-divider />

      <div class="article-content">
        <h3>文章内容</h3>
        <div class="content-box">{{ article.content }}</div>
      </div>

      <n-divider />

      <!-- 文章图片展示区域 -->
      <div v-if="articleImages.length > 0" class="article-images">
        <h3>文章图片</h3>
        <n-grid :cols="3" :x-gap="12" :y-gap="12">
          <n-grid-item v-for="(image, index) in articleImages" :key="index">
            <n-card hoverable>
              <template #cover>
                <img :src="image.imageUrl" class="article-image" />
              </template>
            </n-card>
          </n-grid-item>
        </n-grid>
      </div>

      <n-divider />

      <div class="action-buttons" v-if="article.status === 'pendingReview'">
        <n-space>
          <n-button type="success" @click="handleApprove">通过审核</n-button>
          <n-button type="error" @click="handleReject">拒绝审核</n-button>
        </n-space>
      </div>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useMessage } from 'naive-ui';
import { AdminManagementApi } from '@/api/new/AdminManagementApi';
import { TravelNoteApi } from '@/api/new/travelNoteApi';
import { parseTagsJson } from './columns';

const route = useRoute();
const router = useRouter();
const message = useMessage();

const article = ref({
  articleID: 0,
  authorID: 0,
  title: '',
  content: '',
  favoriteCount: 0,
  commentCount: 0,
  creationTime: new Date(),
  longitude: 0,
  latitude: 0,
  tag: '',
  status: 'pendingReview',
});

const articleImages = ref<any[]>([]);
const loading = ref(false);

// 状态映射
const statusMap = {
  draft: '草稿',
  published: '已发布',
  pendingReview: '待审核',
  deleted: '已删除',
};

// 状态标签类型映射
const statusTypeMap = {
  draft: 'default',
  published: 'success',
  pendingReview: 'warning',
  deleted: 'error',
};

onMounted(async () => {
  const articleId = route.params.id;
  if (articleId) {
    loading.value = true;
    try {
      // 使用 TravelNoteApi 的浏览游记方法获取文章详情
      const articleData = await TravelNoteApi.browseTravelNote(Number(articleId));
      if (articleData) {
        article.value = articleData;
      }

      // 获取文章图片
      try {
        const images = await TravelNoteApi.getArticleImages(Number(articleId));
        console.log('详情页获取到的图片数据:', images)
        if (images && Array.isArray(images)) {
          articleImages.value = images;
        }
      } catch (error: any) {
        console.error('获取文章图片失败:', error);
        // 图片获取失败不影响整体功能
      }
    } catch (error: any) {
      message.error('获取文章详情失败: ' + error.message);
      // 如果API调用失败，使用模拟数据
      article.value = {
        articleID: Number(articleId),
        authorID: 1001,
        title: '示例文章标题',
        content: '这是文章的详细内容，包含了丰富的旅游信息和个人体验...',
        favoriteCount: 45,
        commentCount: 32,
        creationTime: new Date(),
        longitude: 116.404,
        latitude: 39.915,
        tag: '旅游,美食,文化',
        status: 'pendingReview',
      };
    } finally {
      loading.value = false;
    }
  }
});

// 格式化日期
function formatDate(date) {
  if (!date) return '';
  return new Date(date).toLocaleString();
}

// 获取状态文本
function getStatusText(status) {
  return statusMap[status] || status;
}

// 获取状态标签类型
function getStatusType(status) {
  return statusTypeMap[status] || 'default';
}

// 解析标签
function parseTags(tagJson: string): string[] {
  try {
    if (!tagJson) return [];
    const tagData = JSON.parse(tagJson);
    if (tagData && tagData.items && Array.isArray(tagData.items)) {
      return tagData.items.map((item: { tag: string }) => item.tag);
    }
    return [];
  } catch (error: any) {
    console.error('解析标签失败:', error, tagJson);
    return [];
  }
}

// 通过审核
async function handleApprove() {
  try {
    await AdminManagementApi.publishArticle(article.value.articleID);
    message.success('审核通过成功');
    article.value.status = 'published';
  } catch (error: any) {
    message.error('操作失败: ' + error.message);
  }
}

// 拒绝审核
async function handleReject() {
  try {
    await AdminManagementApi.draftArticle(article.value.articleID);
    message.success('已拒绝并退回为草稿');
    article.value.status = 'draft';
  } catch (error: any) {
    message.error('操作失败: ' + error.message);
  }
}
</script>

<style lang="less" scoped>
.article-content {
  margin: 16px 0;

  .content-box {
    padding: 16px;
    background-color: #f9f9f9;
    border-radius: 4px;
    min-height: 200px;
    white-space: pre-wrap;
  }
}

.article-images {
  margin: 16px 0;

  .article-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
    border-radius: 4px;
  }
}

.action-buttons {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style>
